<template>
  <ContentWrap>
    <!-- <div class="font-size-24px font-700">{{ route.meta.title }}</div> -->
    <el-form :inline="true" ref="formRef" :model="form" :rules="rules" label-width="180px"
      class="demo-form-inline mt-20px" v-loading="loading">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name" label="定时任务名称">
            <el-input :disabled="isView" v-model="form.name" class="!w-250px" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否推送" label-width="120px">
            <el-checkbox :disabled="isView" v-model="form.isPublic" label=" " />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="triggerTime" label="触发时间">
            <el-time-picker :disabled="isView" v-model="form.triggerTime" value-format="HH:mm:ss" class="!w-250px"
              placeholder="请选择" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="jobType" label="任务类型" label-width="120px">
            <el-select :disabled="isView" v-model="form.jobType" class="!w-250px" placeholder="请选择" clearable
              @change="form.jobDate = []">
              <el-option label="日任务" :value="0" />
              <el-option label="周任务" :value="1" />
              <el-option label="月任务" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-if="form.jobType === 1">
          <el-form-item prop="jobDate" label="星期">
            <el-checkbox-group :disabled="isView" v-model="form.jobDate">
              <el-checkbox label="星期一" value="2" />
              <el-checkbox label="星期二" value="3" />
              <el-checkbox label="星期三" value="4" />
              <el-checkbox label="星期四" value="5" />
              <el-checkbox label="星期五" value="6" />
              <el-checkbox label="星期六" value="7" />
              <el-checkbox label="星期日" value="1" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.jobType === 2">
          <el-form-item prop="jobDate" label="日期">
            <el-checkbox-group :disabled="isView" v-model="form.jobDate">
              <el-checkbox v-for="item in getMonthDay()" :label="item" :value="item + ''" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="statMagnitude" label="震级范围" class="remove_margin">
            <el-input-number :disabled="isView" v-model="form.statMagnitude" controls-position="right"
              class="!w-90px" />
            <el-select :disabled="isView" v-model="form.statType" class="!w-60px">
              <el-option label="≤" value="≤" />
              <el-option label="<" value="<" />
            </el-select>
          </el-form-item>
          <el-form-item prop="endMagnitude" label="震级" label-width="55">
            <el-select :disabled="isView" v-model="form.endType" class="!w-60px">
              <el-option label="≤" value="≤" />
              <el-option label="<" value="<" />
              <el-option label="=" value="=" />
            </el-select>
            <el-input-number :disabled="isView" v-model="form.endMagnitude" controls-position="right" class="!w-90px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="statDepth" label="震源深度范围" class="remove_margin" label-width="120px">
            <el-input-number :disabled="isView" v-model="form.statDepth" controls-position="right" class="!w-90px" />
            <el-select :disabled="isView" v-model="form.statType2" class="!w-60px">
              <el-option label="≤" value="≤" />
              <el-option label="<" value="<" />
            </el-select>
          </el-form-item>
          <el-form-item prop="endDepth" label="深度" label-width="55">
            <el-select :disabled="isView" v-model="form.endType2" class="!w-60px">
              <el-option label="≤" value="≤" />
              <el-option label="<" value="<" />
              <el-option label="=" value="=" />
            </el-select>
            <el-input-number :disabled="isView" v-model="form.endDepth" controls-position="right" class="!w-90px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="13">
          <el-form-item prop="epifocusType" label="震中方式">
            <el-select :disabled="isView" v-model="form.epifocusType" class="!w-250px">
              <el-option label="区域范围" :value="1" />
              <el-option label="经纬度范围" :value="2" />
              <el-option label="给定列表" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="form.epifocusType !== 3">
          <el-form-item>
            <el-radio-group :disabled="isView" v-model="form.random">
              <el-radio :value="0">按省行政区随机</el-radio>
              <el-radio :value="1">按经纬度间隔随机</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="form.random === 1">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="longitudeInterval" label="经度间隔" label-width="80">
                <el-input :disabled="isView" v-model="form.longitudeInterval" placeholder="请输入" class="!w-100px"
                  clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="latitudeInterval" label="纬度间隔" label-width="80">
                <el-input :disabled="isView" v-model="form.latitudeInterval" placeholder="请输入" class="!w-100px"
                  clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-if="form.epifocusType === 1">
          <el-form-item label=" ">
            <UploadFile :disabled="isView" v-model="form.fileNames" :updateUrl="uploadUrl"
              :downloadFileUrl="downloadFileUrl" @uploadSuccess="uploadSuccess" @removeFile="removeFile" :limit="1">
            </UploadFile>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.epifocusType === 3">
          <el-form-item prop="epifocusList" label="震中位置列表">
            <el-input :disabled="isView" v-model="form.epifocusList" :rows="3" type="textarea" placeholder="震中位置"
              class="!w-500px" />
          </el-form-item>
          <div class="ml-180px c-#999">每行一个经纬度坐标，经纬度以英文分号;分割，最多支持100个坐标</div>
        </el-col>
        <el-col :span="24" v-if="form.epifocusType === 2">
          <el-form-item prop="longitudeRange" label="经度范围">
            <el-input :disabled="isView" v-model="statLongitudeRange" class="!w-150px" placeholder="请输入" clearable
              @blur="calculateLongitudeRange" />&emsp;至&emsp;
            <el-input :disabled="isView" v-model="endLongitudeRange" class="!w-150px" placeholder="请输入" clearable
              @blur="calculateLongitudeRange" />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.epifocusType === 2">
          <el-form-item prop="latitudeRange" label="纬度范围">
            <el-input :disabled="isView" v-model="statLatitudeRange" class="!w-150px" placeholder="请输入" clearable
              @blur="calculateLatitudeRange" />&emsp;至&emsp;
            <el-input :disabled="isView" v-model="endLatitudeRange" class="!w-150px" placeholder="请输入" clearable
              @blur="calculateLatitudeRange" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <LoadMap :fileidInfo="fileidInfo" style="height:400px" v-show='form.epifocusType == 1' /> -->
      <LoadMap :fileidInfo="fileidInfo" style="height:400px" />
      <el-form-item class="el-form-item_operate w-100% mt-30px">
        <el-button v-if="props.timingTriggerData.type !== 'view'" type="primary"
          @click="onSubmit(formRef)">保存</el-button>
        <el-button @click="onClose">关闭</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<script setup>
import { ref, reactive, defineEmits } from 'vue'
import UploadFile from '@/views/responseLevel/populationDensity/create/UploadFile.vue'
import * as timingTrigger from '@/api/earthquake/timingTrigger'
import { useTagsViewStore } from '@/store/modules/tagsView'
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
const emit = defineEmits(['CreateFlag']);
const tagsViewStore = useTagsViewStore()
const message = useMessage() // 消息弹窗
const route = useRoute()
const router = useRouter()
const uploadUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/att/uploadShpFile1')
const downloadFileUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/att/downLoadFile')
const loading = ref(false)
const formRef = ref()
const days = ref([])
const props = defineProps({
  timingTriggerData: {
    type: Object,
    default: {}
  }
})
console.log(props.timingTriggerData,'');
const form = ref({
  name: '',
  triggerTime: null,
  isPublic: false,
  jobDay: null,
  jobDate: [],
  jobType: 0,
  statMagnitude: null,
  endMagnitude: null,
  statType: '≤',
  endType: '≤',
  statDepth: null,
  endDepth: null,
  statType2: '≤',
  endType2: '≤',
  epifocusType: 1,
  random: 0,
  region: null,
  longitudeInterval: '',
  latitudeInterval: '',
  fileId: '',
  fileNames: [],
  epifocusList: '',
  longitudeRange: '',
  latitudeRange: ''
})
const statLongitudeRange = ref()
const endLongitudeRange = ref()
const statLatitudeRange = ref()
const endLatitudeRange = ref()
const isView = ref(props.timingTriggerData.type === 'view')
const rules = reactive({
  name: [{ required: true, message: '请输入定时任务名称', trigger: 'blur' }],
  triggerTime: [{ required: true, message: '请选择触发时间', trigger: 'change' }],
  jobDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
  jobType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  statMagnitude: [{ required: true, message: '请输入震级范围', trigger: 'blur' }],
  endMagnitude: [{ required: true, message: '请输入震级范围', trigger: 'blur' }],
  statDepth: [{ required: true, message: '请输入震源深度范围', trigger: 'blur' }],
  endDepth: [{ required: true, message: '请输入震源深度范围', trigger: 'blur' }],
  epifocusType: [{ required: true, message: '请选择震中方式', trigger: 'change' }],
  longitudeRange: [{ required: true, message: '请输入经度范围', trigger: 'blur' }],
  latitudeRange: [{ required: true, message: '请输入纬度范围', trigger: 'blur' }],
  epifocusList: [{ required: true, message: '请输入震中位置', trigger: 'blur' }],
  longitudeInterval: [{ required: true, message: '请输入经度间隔', trigger: 'blur' }],
  latitudeInterval: [{ required: true, message: '请输入纬度间隔', trigger: 'blur' }]
})

const fileidInfo = ref({
  fileid: props.timingTriggerData.type == 'create' ? '' : 'earthquakeJob_' + props.timingTriggerData.id,
  type: props.timingTriggerData.type == 'create' ? 0 :1,
  query:{
    tableName: props.timingTriggerData.type == 'create' ? 'temp_shp_data' :'earthquake_shp',
    fields: props.timingTriggerData.type == 'create' ?'id': 'id,p_id,province,city',
    owner:"public"
  }
});
watch(
  () => form.value.jobType,
  (v) => {
    form.value.jobDate.value = []
    if (!v) form.value.jobDay = null
  }
)
watch(
  () => form.value.epifocusType,
  (v) => {
    if (v === 1) {
      statLongitudeRange.value = ''
      endLongitudeRange.value = ''
      statLatitudeRange.value = ''
      endLatitudeRange.value = ''
      form.value.longitudeRange = ''
      form.value.latitudeRange = ''
      form.value.epifocusList = ''
    } else if (v === 2) {
      form.value.fileId = ''
      form.value.fileNames = []
      form.value.epifocusList = ''
    } else if (v === 3) {
      form.value.random = 0
      form.value.longitudeInterval = ''
      form.value.latitudeInterval = ''
      statLongitudeRange.value = ''
      endLongitudeRange.value = ''
      statLatitudeRange.value = ''
      endLatitudeRange.value = ''
      form.value.longitudeRange = ''
      form.value.latitudeRange = ''
      form.value.fileId = ''
      form.value.fileNames = []
    }
  }
)

// 获取当前月有多少日
const getMonthDay = () => {
  const date = new Date()
  date.setMonth(date.getMonth() + 1)
  date.setDate(0)
  const days = date.getDate()
  return days
}

const getJobView = async () => {
  loading.value = true
  try {
    form.value = await timingTrigger.getJob(props.timingTriggerData.id)
    form.value.jobDate = form.value.jobDay.split(',')
    form.value.epifocusList = form.value.epifocusList.replace(/;/g, ';\n')
    statLongitudeRange.value = form.value.longitudeRange.split(',')[0]
    endLongitudeRange.value = form.value.longitudeRange.split(',')[1]
    statLatitudeRange.value = form.value.latitudeRange.split(',')[0]
    endLatitudeRange.value = form.value.latitudeRange.split(',')[1]
    if (form.value.fileNames) {
      form.value.fileNames = form.value.fileNames.map((item) => {
        return { name: item, url: form.value.fileId, attachId: form.value.fileId }
      })
    } else {
      form.value.fileNames = []
    }
  } finally {
    loading.value = false
  }
}

// 上传成功
const uploadSuccess = (file) => {
  form.value.fileId = file[0].attachId;
  fileidInfo.value.fileid = file[0].id;
   fileidInfo.value.type = 0;
  fileidInfo.value.query.tableName = "temp_shp_data";
  fileidInfo.value.query.fields = "id";
  fileidInfo.value.fileid = file[0].id;
}

// 删除文件
const removeFile = (file) => {
  form.value.fileId = ''
  timingTrigger.deleteFile(file.attachId);
  fileidInfo.value.fileid = ''
}

// 计算经度范围
const calculateLongitudeRange = () => {
  const arr = [statLongitudeRange.value, endLongitudeRange.value]
  form.value.longitudeRange = arr.join(',')
  console.log(form.value.longitudeRange)
}

// 计算纬度范围
const calculateLatitudeRange = () => {
  const arr = [statLatitudeRange.value, endLatitudeRange.value]
  form.value.latitudeRange = arr.join(',')
  console.log(form.value.latitudeRange)
}

// 保存
const onSubmit = async (formEl) => {
  if (!formEl) return
  if (form.value.epifocusType === 1 && form.value.fileId === '') {
    message.warning('请上传shp文件压缩包')
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      form.value.jobDay = form.value.jobDate.join(',')
      form.value.epifocusList = form.value.epifocusList.replace(/[\n]+/g, '')
      if (!form.value.fileNames.length) form.value.fileId = ''
      try {
        const res =
          props.timingTriggerData.type === 'update'
            ? await timingTrigger.updateJob(form.value)
            : await timingTrigger.addJob(form.value)
            console.log(res,'----');
        onClose()
      } catch (error) {
        console.log(error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 关闭
const onClose = () => {
  let addflag = true
  emit('CreateFlag', addflag)
}

/** 初始化 **/
onMounted(() => {
  if (props.timingTriggerData.type === 'update' || props.timingTriggerData.type === 'view') {
    getJobView()
  }
})
</script>
<style lang="scss" scoped>
.el-form-item_operate {
  :deep(.el-form-item__content) {
    justify-content: center;
  }
}
.remove_margin {
  margin-right: 12px;
}
</style>
